package com.sunlee.admin.api.module.mall.controller;

import com.sunlee.admin.api.annotation.LogOperation;
import com.sunlee.common.core.constant.Constant;
import com.sunlee.common.core.entity.PageData;
import com.sunlee.common.core.entity.Result;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.service.dto.CategoryDTO;
import com.sunlee.common.service.dto.ProductDTO;
import com.sunlee.common.service.entity.ProductCategoryMappingEntity;
import com.sunlee.common.service.service.ProductCategoryMappingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author sunjulei
 * @date 2022/6/27
 */
@RestController
@RequestMapping("/productCategory")
@Api(tags = "商品分类映射表")
public class ProductCategoryController {

    @Autowired
    private ProductCategoryMappingService service;

    /**
     * 通过分类ID分页查询可关联 或 已关联商品
     */
    @GetMapping("/relateProduct/page")
    @ApiOperation("分页")
    @RequiresPermissions("category:page")
    public Result<PageData<ProductDTO>> pageByCid(@ApiIgnore @RequestParam Map<String, Object> params) {

        long id = Long.parseLong((String) params.getOrDefault(Constant.ID, "0"));
        if (id <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_CATEGORY_ID);
        }

        int type = Integer.parseInt((String) params.getOrDefault(Constant.TYPE, "0"));

        String title = (String) params.getOrDefault(Constant.TITLE, "");

        String productId = (String) params.get(Constant.PRODUCT_ID);
        Long pId = null;
        if (StringUtils.isNotBlank(productId)) {
            pId = Long.valueOf(productId);
        }

        return Result.ok(service.pageRelatedByCid(params, id, type,pId,title));
    }

    /**
     * 通过分类Id关联多个商品
     */
    @PostMapping("/saveProduct/{categoryId}")
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("category:save")
    public Result<Object> saveByCid(@PathVariable("categoryId") Long categoryId,
                                    @RequestBody Long[] ids) {

        if (categoryId == null || categoryId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_CATEGORY_ID);
        }
        List<ProductCategoryMappingEntity> saveEntityList = Arrays.stream(ids).map(pId -> {
            ProductCategoryMappingEntity entity = new ProductCategoryMappingEntity();
            entity.setCategoryId(categoryId);
            entity.setProductId(pId);
            return entity;
        }).collect(Collectors.toList());

        service.insertBatchOwn(saveEntityList);
        return Result.ok();
    }

    /**
     * 通过分类ID删除关联
     */
    @PostMapping("/deleteProduct/{categoryId}")
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("category:save")
    public Result<Object> deleteByCid(@PathVariable("categoryId") Long categoryId,
                                      @RequestBody Long[] ids) {

        if (categoryId == null || categoryId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_CATEGORY_ID);
        }

        return Result.ok(service.deleteByCIdAndPIds(categoryId, ids));
    }


    /**
     * 通过商品ID分页查询分类列表
     */
    @GetMapping("/relateCategory/page")
    @ApiOperation("分页")
    @RequiresPermissions("category:page")
    public Result<PageData<CategoryDTO>> pageByPid(@ApiIgnore @RequestParam Map<String, Object> params) {

        long pid = Long.parseLong((String) params.getOrDefault(Constant.PID, "0"));
        if (pid <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }

        return Result.ok(service.pageRelatedByPid(params, pid));
    }


    /**
     * 通过商品Id关联多个分类
     */
    @PostMapping("/saveCategory/{productId}")
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("category:save")
    public Result<Object> saveByPid(@PathVariable("productId") Long productId,
                                    @RequestBody Long[] ids) {

        if (productId == null || productId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }
        List<ProductCategoryMappingEntity> saveEntityList = Arrays.stream(ids).map(cId -> {
            ProductCategoryMappingEntity entity = new ProductCategoryMappingEntity();
            entity.setCategoryId(cId);
            entity.setProductId(productId);
            return entity;
        }).collect(Collectors.toList());

        service.insertBatchOwn(saveEntityList);
        return Result.ok();
    }

    /**
     * 通过商品ID删除关联
     */
    @PostMapping("/deleteCategory/{productId}")
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("category:save")
    public Result<Object> deleteByPid(@PathVariable("productId") Long productId,
                                      @RequestBody Long[] ids) {

        if (productId == null || productId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }

        return Result.ok(service.deleteByPIdAndCIds(productId, ids));
    }
}
